/***************************************************************************
 *   Copyright (C) 2008 by Luca Lanziani   *
 *   luca@tulug.it   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "chat.h"

int main(int argc, char *argv[]) {
  struct sockaddr_in server_socket;
  int options;
  int server_socket_id;
  pthread_t thread;
  struct thread_arg *arg;
  /* set default port */
  int port=12345;

  //signal(SIGPIPE,SIG_IGN);
  signal(SIGINT,close_connections);
  signal(SIGQUIT,close_connections);
  signal(SIGTSTP,close_connections);



  /* parameter */
  while ((options = getopt(argc, argv, "hp:")) != EOF)
    {
      switch (options)
        {
        case 'h':
          //print_help();
          break;
        case 'p':
          port = atoi(optarg);
          break;
        default :
          //help(argv[0]);
          break;
        }
    }


  if (server_socket_id=inizialize_socket(&server_socket,port)<0)
    {
      printf(_("can't open socket"));
      return EXIT_FAILURE;
    }
  
  init_connections_list();

  while (1)
    {
      arg=(struct thread_arg *) malloc(sizeof(struct thread_arg));
      if ((arg->thread_socket_id=accept(server_socket_id,(struct sockaddr *) &arg->thread_socket,&arg->thread_socket_len))<=0)
        {
          //printf(_("Error on accept\n"));
        }
      else
        {
          /* create a thread for the client*/
          if (0!=pthread_create(&thread,NULL,(void*)&start_routine,arg))
            {
              printf(_("Error on pthread_create\n"));
            }
          if (pthread_detach(thread)!=0)
            {
              printf(_("Error on pthread_detach\n"));
            }

          printf(_("Thread %d created\n"),(pthread_t)thread);
        }
    }

  return EXIT_SUCCESS;
}
